import { useQuery } from '@tanstack/react-query';
import { ethers } from 'ethers';
import { useWeb3 } from './useWeb3';
import { useAuthStore } from '@/store/auth';
import { useChain } from '@/context/ChainContext';
import { formatTokenAmount } from '@/lib/utils';

// Vesting Contract ABI - 只包含讀取函數
const VESTING_READ_ABI = [
  "function getBeneficiarySummary(address beneficiary) view returns (uint256 totalVested, uint256 totalReleased, uint256 totalReleasable, uint256 scheduleCount)",
  "function getBeneficiarySchedules(address beneficiary) view returns (bytes32[] scheduleIds)",
  "function getVestingSchedule(bytes32 scheduleId) view returns (address beneficiary, uint256 totalAmount, uint256 startTime, uint256 releasedAmount, uint256 releasableAmount, bool revoked, string category)",
];

interface VestingSchedule {
  schedule_id: string;
  beneficiary: string;
  total_amount: string;
  start_time: number;
  released_amount: string;
  releasable_amount: string;
  revoked: boolean;
  category: string;
  total_amount_formatted: string;
  released_amount_formatted: string;
  releasable_amount_formatted: string;
  start_time_iso: string;
}

interface VestingSummary {
  total_vested: string;
  total_released: string;
  total_releasable: string;
  schedule_count: number;
  total_vested_formatted: string;
  total_released_formatted: string;
  total_releasable_formatted: string;
}

export function useVestingData(contractAddress: string, walletAddress?: string) {
  const { provider } = useWeb3();
  const { getAdminForChain } = useAuthStore();
  const { currentChain } = useChain();
  
  const admin = getAdminForChain(currentChain);
  // Use provided wallet address or fall back to admin wallet
  const queryAddress = walletAddress || admin?.wallet_address;

  return useQuery({
    queryKey: ['vestingData', queryAddress, contractAddress, currentChain],
    queryFn: async () => {
      if (!provider || !contractAddress || !queryAddress) {
        return null;
      }

      // 創建只讀合約實例
      const contract = new ethers.Contract(contractAddress, VESTING_READ_ABI, provider);
      
      try {
        // 1. 獲取摘要信息
        let summary;
        try {
          summary = await contract.getBeneficiarySummary(queryAddress);
        } catch (error: any) {
          // 如果返回空數據，表示沒有 vesting
          if (error.code === 'BAD_DATA' || error.value === '0x') {
            return null; // 沒有 vesting 數據
          }
          throw error;
        }
        
        // 檢查是否有 vesting 數據
        if (!summary || Number(summary.scheduleCount) === 0) {
          return null; // 沒有 vesting 數據
        }
        
        // 2. 獲取所有 schedule IDs
        let scheduleIds;
        try {
          scheduleIds = await contract.getBeneficiarySchedules(queryAddress);
        } catch (error: any) {
          // 如果返回空數據，表示沒有 schedules
          if (error.code === 'BAD_DATA' || error.value === '0x') {
            return null;
          }
          throw error;
        }
        
        // 3. 並行獲取每個 schedule 的詳細信息
        const schedulePromises = scheduleIds.map(async (scheduleId: string) => {
          const schedule = await contract.getVestingSchedule(scheduleId);
          
          // 解構返回的數組或對象
          const [beneficiary, totalAmount, startTime, releasedAmount, releasableAmount, revoked, category] = 
            Array.isArray(schedule) ? schedule : [
              schedule.beneficiary,
              schedule.totalAmount,
              schedule.startTime,
              schedule.releasedAmount,
              schedule.releasableAmount,
              schedule.revoked,
              schedule.category
            ];
          
          return {
            schedule_id: scheduleId,
            beneficiary: beneficiary,
            total_amount: totalAmount.toString(),
            start_time: Number(startTime),
            released_amount: releasedAmount.toString(),
            releasable_amount: releasableAmount.toString(),
            revoked: revoked,
            category: category,
            total_amount_formatted: formatTokenAmount(ethers.formatEther(totalAmount)),
            released_amount_formatted: formatTokenAmount(ethers.formatEther(releasedAmount)),
            releasable_amount_formatted: formatTokenAmount(ethers.formatEther(releasableAmount)),
            start_time_iso: new Date(Number(startTime) * 1000).toISOString(),
          };
        });
        
        const schedules = await Promise.all(schedulePromises);
        
        // 格式化摘要數據
        const formattedSummary: VestingSummary = {
          total_vested: summary.totalVested.toString(),
          total_released: summary.totalReleased.toString(),
          total_releasable: summary.totalReleasable.toString(),
          schedule_count: Number(summary.scheduleCount),
          total_vested_formatted: formatTokenAmount(ethers.formatEther(summary.totalVested)),
          total_released_formatted: formatTokenAmount(ethers.formatEther(summary.totalReleased)),
          total_releasable_formatted: formatTokenAmount(ethers.formatEther(summary.totalReleasable)),
        };

        return {
          wallet_address: queryAddress,
          summary: formattedSummary,
          schedules,
        };
      } catch (error: any) {
        console.error('Error fetching vesting data:', error);
        // 如果是 BAD_DATA 錯誤，返回 null 而不是拋出錯誤
        if (error.code === 'BAD_DATA' || error.value === '0x') {
          return null;
        }
        throw error;
      }
    },
    enabled: !!provider && !!contractAddress && !!queryAddress,
    staleTime: 30000, // 30 秒緩存
    gcTime: 5 * 60 * 1000, // 5 分鐘垃圾回收
  });
}